package com.haust.leyou.controller;

import com.haust.leyou.pojo.Category;
import com.haust.leyou.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @Auther: csp1999
 * @Date: 2020/12/08/15:28
 * @Description:
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 根据父节点查询商品类目
     *
     * @param pid 父类目id
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<Category>> queryCategoriesByPid(
            @RequestParam(value = "pid", defaultValue = "0") Long pid) {

        try {
            // 状态码400: 参数不合法
            if (pid == null || pid < 0) {
//                return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
//                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
                return ResponseEntity.badRequest().build();
            }
            List<Category> categoryList = categoryService.queryCategoryByPid(pid);
            if (CollectionUtils.isEmpty(categoryList)) {
                // 状态码404: 服务器没有找到目标资源
//                return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
                return ResponseEntity.notFound().build();
            }

            // 状态码200: 资源获取成功！
            return ResponseEntity.ok(categoryList);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 状态码500: 出现异常,服务器内部错误
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }

    /**
     * 根据分类ids集合 得到商品分类Category集合的名称集合
     *
     * @param ids
     * @return
     */
    @GetMapping
    public ResponseEntity<List<String>> queryNamesByIds(@RequestParam("ids") List<Long> ids) {

        List<String> nameList = categoryService.queryNamesByIds(ids);

        if (CollectionUtils.isEmpty(nameList)) {
            // 状态码404: 服务器没有找到目标资源
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
            return ResponseEntity.notFound().build();
        }

        // 状态码200: 资源获取成功！
        return ResponseEntity.ok(nameList);
    }
}
